<!--
  创建考试页面
-->
<template>
  <div class="exam-create">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button
          text
          :icon="ArrowLeft"
          @click="goBack"
          class="back-btn"
        >
          返回考试列表
        </el-button>
        <h1>创建考试</h1>
        <p>设置考试基本信息和配置</p>
      </div>
      <div class="header-right">
        <el-button @click="goBack">取消</el-button>
        <el-button @click="saveDraft" :loading="saving">
          保存草稿
        </el-button>
        <el-button
          type="primary"
          :loading="saving"
          @click="publishExam"
        >
          发布考试
        </el-button>
      </div>
    </div>

    <!-- 创建步骤 -->
    <el-card>
      <el-steps :active="currentStep" align-center>
        <el-step title="基本信息" description="设置考试基本信息" />
        <el-step title="题目配置" description="选择或创建考试题目" />
        <el-step title="考试设置" description="配置考试规则和限制" />
        <el-step title="确认发布" description="检查信息并发布考试" />
      </el-steps>
    </el-card>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 步骤1: 基本信息 -->
      <div v-if="currentStep === 0" class="step-panel">
        <el-form
          ref="basicFormRef"
          :model="examForm"
          :rules="basicRules"
          label-width="120px"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="考试标题" prop="title">
                <el-input
                  v-model="examForm.title"
                  placeholder="请输入考试标题"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考试类型" prop="exam_type">
                <el-select v-model="examForm.exam_type" style="width: 100%">
                  <el-option label="正式考试" value="formal" />
                  <el-option label="模拟考试" value="practice" />
                  <el-option label="作业练习" value="homework" />
                  <el-option label="随堂测验" value="quiz" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="考试描述" prop="description">
            <el-input
              v-model="examForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入考试描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="start_time">
                <el-date-picker
                  v-model="examForm.start_time"
                  type="datetime"
                  placeholder="选择开始时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="end_time">
                <el-date-picker
                  v-model="examForm.end_time"
                  type="datetime"
                  placeholder="选择结束时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="考试时长" prop="duration">
                <el-input-number
                  v-model="examForm.duration"
                  :min="5"
                  :max="480"
                  style="width: 100%"
                />
                <div class="form-unit">分钟</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="满分" prop="total_score">
                <el-input-number
                  v-model="examForm.total_score"
                  :min="10"
                  :max="1000"
                  style="width: 100%"
                />
                <div class="form-unit">分</div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="及格分" prop="passing_score">
                <el-input-number
                  v-model="examForm.passing_score"
                  :min="0"
                  :max="examForm.total_score"
                  style="width: 100%"
                />
                <div class="form-unit">分</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="最大参与人数" prop="max_participants">
                <el-input-number
                  v-model="examForm.max_participants"
                  :min="1"
                  :max="9999"
                  style="width: 100%"
                />
                <div class="form-tip">留空表示无限制</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="尝试次数" prop="max_attempts">
                <el-input-number
                  v-model="examForm.max_attempts"
                  :min="1"
                  :max="10"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="考试标签">
            <el-select
              v-model="examForm.tags"
              multiple
              filterable
              allow-create
              placeholder="添加标签"
              style="width: 100%"
            >
              <el-option
                v-for="tag in commonTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <div class="step-actions">
          <el-button size="large" @click="goBack">取消</el-button>
          <el-button type="primary" size="large" @click="nextStep">
            下一步：配置题目
          </el-button>
        </div>
      </div>

      <!-- 步骤2: 题目配置 -->
      <div v-if="currentStep === 1" class="step-panel">
        <div class="question-config">
          <!-- 题目选择方式 -->
          <el-card class="config-card">
            <h3>选择题目方式</h3>
            <el-radio-group v-model="questionSelectionType" @change="handleSelectionTypeChange">
              <el-radio value="manual">手动选择</el-radio>
              <el-radio value="paper">从试卷选择</el-radio>
              <el-radio value="auto">智能组卷</el-radio>
            </el-radio-group>
          </el-card>

          <!-- 手动选择题目 -->
          <el-card v-if="questionSelectionType === 'manual'" class="config-card">
            <div class="question-selector">
              <div class="selector-header">
                <h3>选择考试题目</h3>
                <div class="selector-info">
                  已选择 {{ selectedQuestions.length }} 道题目，总分 {{ selectedTotalScore }} 分
                </div>
              </div>

              <!-- 筛选器 -->
              <div class="question-filter">
                <el-form :inline="true">
                  <el-form-item label="题库">
                    <el-select
                      v-model="questionFilter.question_bank"
                      placeholder="选择题库"
                      clearable
                      style="width: 200px"
                    >
                      <el-option
                        v-for="bank in questionBanks"
                        :key="bank.id"
                        :label="bank.name"
                        :value="bank.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="类型">
                    <el-select
                      v-model="questionFilter.question_type"
                      placeholder="选择类型"
                      clearable
                      style="width: 120px"
                    >
                      <el-option label="单选题" value="single_choice" />
                      <el-option label="多选题" value="multiple_choice" />
                      <el-option label="判断题" value="true_false" />
                      <el-option label="填空题" value="fill_blank" />
                      <el-option label="简答题" value="essay" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="loadAvailableQuestions">
                      筛选
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 题目列表 -->
              <el-table
                :data="availableQuestions"
                @selection-change="handleQuestionSelection"
                max-height="400"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column label="题目" min-width="300">
                  <template #default="{ row }">
                    <div class="question-cell">
                      {{ truncateText(stripHtml(row.content), 100) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="类型" width="100">
                  <template #default="{ row }">
                    <el-tag size="small">{{ getTypeText(row.question_type) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="难度" width="80">
                  <template #default="{ row }">
                    <el-tag size="small" :type="getDifficultyType(row.difficulty)">
                      {{ row.difficulty }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="分值" width="80">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.points"
                      :min="1"
                      :max="100"
                      size="small"
                      @change="updateSelectedTotalScore"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>

          <!-- 从试卷选择 -->
          <el-card v-else-if="questionSelectionType === 'paper'" class="config-card">
            <h3>选择试卷</h3>
            <p>从已有试卷中选择题目</p>
            <el-empty description="试卷选择功能开发中..." />
          </el-card>

          <!-- 智能组卷 -->
          <el-card v-else-if="questionSelectionType === 'auto'" class="config-card">
            <h3>智能组卷</h3>
            <el-form :model="autoPaperConfig" label-width="100px">
              <el-form-item label="题库">
                <el-select v-model="autoPaperConfig.question_bank" style="width: 100%">
                  <el-option
                    v-for="bank in questionBanks"
                    :key="bank.id"
                    :label="bank.name"
                    :value="bank.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="题目数量">
                <el-input-number v-model="autoPaperConfig.question_count" :min="1" :max="100" />
              </el-form-item>
              <el-form-item label="总分">
                <el-input-number v-model="autoPaperConfig.total_points" :min="10" :max="1000" />
              </el-form-item>
              <el-form-item label="难度分布">
                <div class="difficulty-distribution">
                  <el-row :gutter="12">
                    <el-col :span="8">
                      <div class="difficulty-item">
                        <span>简单</span>
                        <el-input-number v-model="autoPaperConfig.easy_count" :min="0" />
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="difficulty-item">
                        <span>中等</span>
                        <el-input-number v-model="autoPaperConfig.medium_count" :min="0" />
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <div class="difficulty-item">
                        <span>困难</span>
                        <el-input-number v-model="autoPaperConfig.hard_count" :min="0" />
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="generateAutoPaper">
                  生成试卷
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <div class="step-actions">
          <el-button size="large" @click="prevStep">上一步</el-button>
          <el-button
            type="primary"
            size="large"
            :disabled="selectedQuestions.length === 0"
            @click="nextStep"
          >
            下一步：考试设置
          </el-button>
        </div>
      </div>

      <!-- 步骤3: 考试设置 -->
      <div v-if="currentStep === 2" class="step-panel">
        <el-form
          ref="settingsFormRef"
          :model="examForm"
          label-width="120px"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-card class="settings-card">
                <h3>基本设置</h3>
                <el-form-item label="随机题目">
                  <el-switch
                    v-model="examForm.randomize_questions"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="form-tip">开启后题目顺序将随机排列</div>
                </el-form-item>
                <el-form-item label="随机选项">
                  <el-switch
                    v-model="examForm.randomize_options"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="form-tip">开启后选择题选项顺序将随机排列</div>
                </el-form-item>
                <el-form-item label="显示结果">
                  <el-switch
                    v-model="examForm.show_results"
                    active-text="立即显示"
                    inactive-text="不显示"
                  />
                  <div class="form-tip">考试结束后是否立即显示成绩</div>
                </el-form-item>
                <el-form-item label="显示答案">
                  <el-switch
                    v-model="examForm.show_answers"
                    active-text="显示"
                    inactive-text="隐藏"
                  />
                  <div class="form-tip">考试结束后是否显示正确答案</div>
                </el-form-item>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="settings-card">
                <h3>时间设置</h3>
                <el-form-item label="延迟开始">
                  <el-switch
                    v-model="examForm.allow_late_start"
                    active-text="允许"
                    inactive-text="不允许"
                  />
                  <div class="form-tip">是否允许考试开始后进入</div>
                </el-form-item>
                <el-form-item label="自动提交">
                  <el-switch
                    v-model="examForm.auto_submit"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="form-tip">时间到后自动提交试卷</div>
                </el-form-item>
                <el-form-item label="防作弊">
                  <el-switch
                    v-model="examForm.anti_cheating"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="form-tip">开启防作弊监控功能</div>
                </el-form-item>
                <el-form-item label="人脸识别">
                  <el-switch
                    v-model="examForm.face_recognition"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                  <div class="form-tip">考试前进行人脸身份验证</div>
                </el-form-item>
              </el-card>
            </el-col>
          </el-row>
        </el-form>

        <div class="step-actions">
          <el-button size="large" @click="prevStep">上一步</el-button>
          <el-button type="primary" size="large" @click="nextStep">
            下一步：确认发布
          </el-button>
        </div>
      </div>

      <!-- 步骤4: 确认发布 -->
      <div v-if="currentStep === 3" class="step-panel">
        <el-card class="summary-card">
          <h3>考试信息确认</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="考试标题">{{ examForm.title }}</el-descriptions-item>
            <el-descriptions-item label="考试类型">{{ examForm.exam_type }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(examForm.start_time) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(examForm.end_time) }}</el-descriptions-item>
            <el-descriptions-item label="考试时长">{{ examForm.duration }} 分钟</el-descriptions-item>
            <el-descriptions-item label="满分">{{ examForm.total_score }} 分</el-descriptions-item>
            <el-descriptions-item label="及格分">{{ examForm.passing_score }} 分</el-descriptions-item>
            <el-descriptions-item label="参与限制">{{ examForm.max_participants || '无限制' }}</el-descriptions-item>
            <el-descriptions-item label="题目数量" :span="2">{{ selectedQuestions.length }} 道</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="questions-summary">
          <h3>题目预览</h3>
          <div class="questions-preview">
            <div
              v-for="(question, index) in selectedQuestions.slice(0, 5)"
              :key="question.id"
              class="question-preview-item"
            >
              <div class="question-number">{{ index + 1 }}.</div>
              <div class="question-content">
                {{ truncateText(stripHtml(question.content), 80) }}
              </div>
              <div class="question-points">{{ question.points }}分</div>
            </div>
            <div v-if="selectedQuestions.length > 5" class="more-questions">
              还有 {{ selectedQuestions.length - 5 }} 道题目...
            </div>
          </div>
        </el-card>

        <div class="step-actions">
          <el-button size="large" @click="prevStep">上一步</el-button>
          <el-button type="primary" size="large" :loading="saving" @click="confirmPublish">
            确认发布考试
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores'
import { questionApi } from '@/api/questions'
import { examinationsApi } from '@/api/examinations'
import { aiApi } from '@/api/ai'
import type { Question, QuestionBank, Examination } from '@/types'
import { ArrowLeft, Check, Clock, Users } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const currentStep = ref(0)
const saving = ref(false)
const questionSelectionType = ref('manual')
const questionBanks = ref<QuestionBank[]>([])
const availableQuestions = ref<Question[]>([])
const selectedQuestions = ref<Question[]>([])

// 表单引用
const basicFormRef = ref<FormInstance>()
const settingsFormRef = ref<FormInstance>()

// 考试表单
const examForm = reactive({
  title: '',
  description: '',
  exam_type: 'formal',
  start_time: '',
  end_time: '',
  duration: 60,
  total_score: 100,
  passing_score: 60,
  max_participants: null as number | null,
  max_attempts: 1,
  tags: [] as string[],
  randomize_questions: false,
  randomize_options: false,
  show_results: true,
  show_answers: false,
  allow_late_start: false,
  auto_submit: true,
  anti_cheating: false,
  face_recognition: false
})

// 智能组卷配置
const autoPaperConfig = reactive({
  question_bank: '',
  question_count: 20,
  total_points: 100,
  easy_count: 5,
  medium_count: 10,
  hard_count: 5
})

// 题目筛选
const questionFilter = reactive({
  question_bank: '',
  question_type: ''
})

// 常用标签
const commonTags = ['期末考试', '期中考试', '单元测试', '模拟考试', '随堂测验']

// 表单验证规则
const basicRules: FormRules = {
  title: [
    { required: true, message: '请输入考试标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  exam_type: [
    { required: true, message: '请选择考试类型', trigger: 'change' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请设置考试时长', trigger: 'change' }
  ],
  total_score: [
    { required: true, message: '请设置满分', trigger: 'change' }
  ],
  passing_score: [
    { required: true, message: '请设置及格分', trigger: 'change' }
  ]
}

// 计算属性
const selectedTotalScore = computed(() => {
  return selectedQuestions.value.reduce((total, question) => total + (question.points || 0), 0)
})

// 加载题库列表
const loadQuestionBanks = async () => {
  try {
    const response = await questionApi.getQuestionBanks({ page_size: 100 })
    questionBanks.value = response.data.results
  } catch (error) {
    console.error('Failed to load question banks:', error)
    ElMessage.error('加载题库失败')
  }
}

// 加载可选题目
const loadAvailableQuestions = async () => {
  try {
    const params: any = {
      page_size: 50,
      is_active: true
    }
    if (questionFilter.question_bank) {
      params.question_bank = questionFilter.question_bank
    }
    if (questionFilter.question_type) {
      params.question_type = questionFilter.question_type
    }

    const response = await questionApi.getQuestions(params)
    // 为题目添加默认分值
    availableQuestions.value = response.data.results.map((q: Question) => ({
      ...q,
      points: q.points || 5 // 默认5分
    }))
  } catch (error: any) {
    console.error('Failed to load questions:', error)
    ElMessage.error(error.message || '加载题目失败')
  }
}

// 处理题目选择变化
const handleQuestionSelection = (selection: Question[]) => {
  selectedQuestions.value = selection
}

// 更新选中题目总分
const updateSelectedTotalScore = () => {
  // 触发计算属性重新计算
  selectedQuestions.value = [...selectedQuestions.value]
}

// 处理选择方式变化
const handleSelectionTypeChange = (type: string) => {
  if (type === 'manual') {
    loadAvailableQuestions()
  }
}

// 智能组卷
const generateAutoPaper = async () => {
  try {
    // 验证配置
    if (!autoPaperConfig.question_bank) {
      ElMessage.warning('请选择题库')
      return
    }

    const totalCount = autoPaperConfig.easy_count + autoPaperConfig.medium_count + autoPaperConfig.hard_count
    if (totalCount === 0) {
      ElMessage.warning('请设置题目数量分布')
      return
    }

    const config = {
      question_bank: autoPaperConfig.question_bank,
      question_count: totalCount,
      difficulty_distribution: {
        easy: autoPaperConfig.easy_count,
        medium: autoPaperConfig.medium_count,
        hard: autoPaperConfig.hard_count
      },
      type_distribution: {},
      tags: []
    }

    // 调用AI智能组卷API
    const response = await aiApi.generateQuestions({
      subject: '智能组卷',
      topic: `${examForm.title || '自动生成'} 智能组卷`,
      question_type: 'mixed',
      difficulty: 'mixed',
      count: totalCount
    })

    if (response.success && response.questions.length > 0) {
      // 转换为Question格式
      selectedQuestions.value = response.questions.map(q => ({
        id: q.id,
        content: q.content,
        title: q.title,
        question_type: q.question_type,
        difficulty: q.difficulty,
        points: Math.round(autoPaperConfig.total_points / totalCount) || 5
      }))

      // 更新考试总分
      examForm.total_score = autoPaperConfig.total_points
      examForm.passing_score = Math.round(autoPaperConfig.total_points * 0.6)

      ElMessage.success(`成功生成 ${selectedQuestions.value.length} 道题目`)
    } else {
      throw new Error('智能组卷失败，未返回有效题目')
    }
  } catch (error: any) {
    console.error('智能组卷失败:', error)
    ElMessage.error(error.message || '智能组卷失败，请重试')
  }
}

// 步骤控制
const nextStep = async () => {
  if (currentStep.value === 0) {
    if (!basicFormRef.value) return
    try {
      await basicFormRef.value.validate()
      // 验证时间逻辑
      if (examForm.start_time && examForm.end_time) {
        const start = new Date(examForm.start_time)
        const end = new Date(examForm.end_time)
        if (end <= start) {
          ElMessage.error('结束时间必须晚于开始时间')
          return
        }
      }
      currentStep.value++
    } catch (error) {
      // 验证失败
    }
  } else if (currentStep.value === 1) {
    if (selectedQuestions.value.length === 0) {
      ElMessage.error('请至少选择一道题目')
      return
    }
    examForm.total_score = selectedTotalScore.value
    currentStep.value++
  } else {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 保存草稿
const saveDraft = async () => {
  if (!basicFormRef.value) return

  try {
    saving.value = true
    await basicFormRef.value.validate()

    const examData = {
      title: examForm.title,
      description: examForm.description,
      exam_type: examForm.exam_type,
      start_time: examForm.start_time,
      end_time: examForm.end_time,
      duration: examForm.duration,
      total_score: examForm.total_score,
      passing_score: examForm.passing_score,
      max_participants: examForm.max_participants,
      max_attempts: examForm.max_attempts,
      tags: examForm.tags,
      status: 'draft',
      settings: {
        randomize_questions: examForm.randomize_questions,
        randomize_options: examForm.randomize_options,
        show_results: examForm.show_results,
        show_answers: examForm.show_answers,
        allow_late_start: examForm.allow_late_start,
        auto_submit: examForm.auto_submit,
        anti_cheating: examForm.anti_cheating,
        face_recognition: examForm.face_recognition
      },
      questions: selectedQuestions.value.map(q => ({
        question: q.id,
        points: q.points || 0,
        order: 0
      }))
    }

    await examinationsApi.createExamination(examData)
    ElMessage.success('草稿保存成功')
    router.push('/examinations/list')
  } catch (error: any) {
    console.error('Failed to save draft:', error)
    ElMessage.error(error.message || '保存失败，请检查输入')
  } finally {
    saving.value = false
  }
}

// 发布考试
const publishExam = async () => {
  if (currentStep.value === 0) {
    nextStep()
    return
  }

  await confirmPublish()
}

// 确认发布
const confirmPublish = async () => {
  try {
    // 确认发布对话框
    await ElMessageBox.confirm(
      `确定要发布考试 "${examForm.title}" 吗？发布后学生即可参加考试。`,
      '确认发布',
      {
        confirmButtonText: '确认发布',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    saving.value = true

    // 验证题目配置
    if (selectedQuestions.value.length === 0) {
      throw new Error('请选择考试题目')
    }

    const actualScore = selectedTotalScore.value
    if (actualScore !== examForm.total_score) {
      throw new Error(`题目总分 (${actualScore}分) 与设置的分值 (${examForm.total_score}分) 不一致`)
    }

    const examData = {
      title: examForm.title,
      description: examForm.description,
      exam_type: examForm.exam_type,
      start_time: examForm.start_time,
      end_time: examForm.end_time,
      duration: examForm.duration,
      total_score: examForm.total_score,
      passing_score: examForm.passing_score,
      max_participants: examForm.max_participants,
      max_attempts: examForm.max_attempts,
      tags: examForm.tags,
      status: 'published',
      settings: {
        randomize_questions: examForm.randomize_questions,
        randomize_options: examForm.randomize_options,
        show_results: examForm.show_results,
        show_answers: examForm.show_answers,
        allow_late_start: examForm.allow_late_start,
        auto_submit: examForm.auto_submit,
        anti_cheating: examForm.anti_cheating,
        face_recognition: examForm.face_recognition
      },
      questions: selectedQuestions.value.map((q, index) => ({
        question: q.id,
        points: q.points || 0,
        order: index + 1
      }))
    }

    await examinationsApi.createExamination(examData)
    ElMessage.success('考试发布成功')
    router.push('/examinations/list')
  } catch (error: any) {
    console.error('Failed to publish exam:', error)
    if (error !== 'cancel') {
      ElMessage.error(error.message || '发布失败，请检查配置')
    }
  } finally {
    saving.value = false
  }
}

// 返回
const goBack = () => {
  router.push('/examinations/list')
}

// 工具函数
const formatDateTime = (dateString: string) => {
  return dateString ? new Date(dateString).toLocaleString() : ''
}

const stripHtml = (html: string) => {
  return html.replace(/<[^>]*>/g, '')
}

const truncateText = (text: string, maxLength: number) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const getTypeText = (type: string) => {
  const types: Record<string, string> = {
    single_choice: '单选',
    multiple_choice: '多选',
    true_false: '判断',
    fill_blank: '填空',
    essay: '简答'
  }
  return types[type] || type
}

const getDifficultyType = (difficulty: string) => {
  const types: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

// 监听选中题目变化，自动更新总分
watch(
  () => selectedQuestions.value.length,
  () => {
    if (currentStep.value === 1) {
      const actualScore = selectedTotalScore.value
      if (actualScore > 0) {
        examForm.total_score = actualScore
        // 更新及格分为60%
        examForm.passing_score = Math.round(actualScore * 0.6)
      }
    }
  }
)

// 页面挂载时加载数据
onMounted(async () => {
  await loadQuestionBanks()
  // 自动加载可用题目
  await loadAvailableQuestions()
})
</script>

<style scoped lang="scss">
.exam-create {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .back-btn {
      margin-bottom: 12px;
    }

    h1 {
      font-size: 28px;
      color: var(--el-text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin: 0;
    }

    .header-right {
      display: flex;
      gap: 12px;
      margin-top: 16px;
    }
  }

  .step-content {
    margin-top: 24px;

    .step-panel {
      background: white;
      border-radius: 8px;
      padding: 24px;
      border: 1px solid var(--el-border-color-light);
    }
  }

  .step-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid var(--el-border-color-light);
  }

  .form-unit {
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-left: 8px;
  }

  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-regular);
    margin-top: 4px;
  }

  .question-config {
    .config-card {
      margin-bottom: 24px;

      h3 {
        font-size: 16px;
        color: var(--el-text-color-primary);
        margin: 0 0 16px 0;
      }

      .question-selector {
        .selector-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          h3 {
            margin: 0;
          }

          .selector-info {
            font-size: 14px;
            color: var(--el-text-color-regular);
          }
        }

        .question-filter {
          background: var(--el-fill-color-light);
          padding: 16px;
          border-radius: 8px;
          margin-bottom: 16px;
        }

        .question-cell {
          font-size: 14px;
          line-height: 1.5;
        }
      }

      .difficulty-distribution {
        .difficulty-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          span {
            font-size: 14px;
            color: var(--el-text-color-regular);
          }
        }
      }
    }
  }

  .settings-card {
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      color: var(--el-text-color-primary);
      margin: 0 0 16px 0;
    }
  }

  .summary-card {
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      color: var(--el-text-color-primary);
      margin: 0 0 16px 0;
    }
  }

  .questions-summary {
    h3 {
      font-size: 16px;
      color: var(--el-text-color-primary);
      margin: 0 0 16px 0;
    }

    .questions-preview {
      .question-preview-item {
        display: flex;
        align-items: flex-start;
        padding: 12px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);

        &:last-child {
          border-bottom: none;
        }

        .question-number {
          width: 30px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }

        .question-content {
          flex: 1;
          font-size: 14px;
          color: var(--el-text-color-regular);
          line-height: 1.5;
          margin: 0 12px;
        }

        .question-points {
          font-size: 14px;
          color: var(--el-color-primary);
          font-weight: 500;
        }
      }

      .more-questions {
        text-align: center;
        padding: 16px 0;
        color: var(--el-text-color-placeholder);
        font-size: 14px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .exam-create {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        flex-direction: column;
      }
    }

    .step-content .step-panel {
      padding: 16px;
    }

    .step-actions {
      flex-direction: column;
      gap: 12px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>